package com.lkm.app_ui.ui;

import android.os.Bundle;
import android.view.View;

import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.MBaseFragment;
import com.lkm.app_ui.R;
import com.lkm.app_ui.RouterUINavigation;
import com.lkm.app_ui.RunTimeData;
import com.lkm.app_ui.help.AppUIHelp;
import com.lkm.app_ui.jz.net.PayApi;
import com.lkm.app_ui.m.fun.DelegatePayTask;
import com.lkm.app_ui.m.fun.FunItem;
import com.lkm.app_ui.m.fun.OnKeyNumberEvent;
import com.lkm.app_ui.ui.sale.SaleContract;
import com.lkm.app_ui.view.choiceCard.ChoiceCard;
import com.lkm.app_ui.view.choiceCard.ChoiceItem;
import com.lkm.app_ui.view.choiceCard.IChoiceItem;
import com.lkm.comlib.help.ViewUIHelp;
import com.lkm.comlib.ui.BaseFragmentActivity;
import com.lkm.frame.otto.LinkBus;
import com.lkm.frame.otto.LinkBusCycleWrapper;
import com.lkm.frame.otto.ObserverAutoNext;
import com.lkm.frame.task2.BackCallAdapter;
import com.lkm.frame.task2.Task;
import com.lkm.frame.util.CycleHelp;
import com.lkm.market2_0.ExpandConfig;
import com.lkm.market2_0.entity.BreedTo;
import com.lkm.market2_0.entity.ResponEntity;
import com.lkm.market2_0.entity.SteelyardInfo;
import com.lkm.market2_0.m_imple.app_main.LoadBreedForSTask;
import com.lkm.market2_0.m.steelyarddata.SteelyardDataModule;
import com.lkm.market2_0.m.steelyardserver.GoodsButtonInfoTo;
import com.lkm.market2_0.m.steelyardserver.OnSteelyardKeyEvent;
import com.lkm.market2_0.m.steelyardserver.SteelyardServerModule;
import com.lkm.market2_0.m_imple.steelyardserver.server.AbsSendWriteTask;
import com.lkm.market2_0.task.DefaultTaskExecutor;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class SaleFunFragment extends MBaseFragment implements ChoiceCard.ChoiceCardBC {

    SaleContract.SubtotalPresenter subtotalPresenter;
    SaleContract.Presenter presenter;

    @Override
    protected boolean configIsLockKey() {
        return true;
    }

    public static SaleFunFragment getInstance(Fragment targetFragment, int requestCode) {
        SaleFunFragment f = new SaleFunFragment();
        Bundle data = new Bundle();
        
        f.setArguments(data);
        f.set(targetFragment, requestCode);

        return f;
    }



    @Override
    protected int configLayoutResID() {
        return R.layout.fragment_fun_sale;
    }

    private ChoiceCard mChoiceCard;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        presenter = SaleContract.presenter;
        subtotalPresenter = SaleContract.subtotalPresenter;

        mChoiceCard = findViewById(R.id.ChoiceCard);

        mChoiceCard.init(false, R.layout.view_choice_card, R.layout.item_fun_p, R.layout.item_fun, 5);

        mChoiceCard.setChoiceCardBC(this);


        if(RunTimeData.isSongjian)
        initDataSongjian();
        else
            initDatax();

    }

    private void initDatax(){
        List<FunItem> funItems = new ArrayList<>();
        funItems.add(new FunItem("0", "0：清空小计"));
        funItems.add(new FunItem("1", "1：修改小计"));

        funItems.add(new FunItem("2", "2：会员积分补刷"));
        funItems.add(new FunItem("3", "3：全支付"));
        funItems.add(new FunItem("4", "4：档口信息管理"));

        funItems.add(new FunItem("5", "5：计件"));
        funItems.add(new FunItem("", ""));



        funItems.add(new FunItem("7", "7：关于设备"));
        funItems.add(new FunItem("8", "8：同步按键商品"));
        funItems.add(new FunItem("9", "9：同步台秤信息"));
        funItems.add(new FunItem("10", "商品提取"));

        ChoiceItem[] cis = new ChoiceItem[funItems.size()];
        int i = 0;
        for (FunItem funItem : funItems) {
            cis[i] = new ChoiceItem(funItem.id, funItem.name);
            cis[i].setTag(funItem);
            i++;
        }

        mChoiceCard.binData(cis);
    }

    private void initDataSongjian(){

//        SteelyardDataModule steelyardDataModule = AppConst.getModuleManager().loadModule(SteelyardDataModule.class);


        List<BreedTo> breedTos = RunTimeData.steelyardInfo.getBreedTo();
        if(breedTos==null)
            breedTos=new ArrayList<>();
        int i = 0;
        ChoiceItem[] cis = new ChoiceItem[breedTos.size()];
        for (BreedTo funItem : breedTos) {
            cis[i] = new ChoiceItem(""+funItem.id, funItem.goods_name);
            cis[i].setTag(funItem);
            i++;
        }

        mChoiceCard.binData(cis);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        reOnKeyEvent();
        reOnKeyNumberEvent();
    }

    
    private void reOnKeyEvent() {
        LinkBusCycleWrapper.register(new ObserverAutoNext<OnSteelyardKeyEvent>() {
            @Override
            public Class<OnSteelyardKeyEvent> getBusEventClass() {
                return OnSteelyardKeyEvent.class;
            }
            @Override
            public void onReceiver(OnSteelyardKeyEvent data) {
                if (!data.isIntercepted()) {
                    data.setIntercepted(true);
                    if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_FUN) {
                        RouterUINavigation.getInstance().dismiss(SaleFunFragment.this);
                    }
                    
                    if(data.getKeyCode() > 10){
                        handNumber(data.getKeyCode(),false);
                    }
                }
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }

    private void reOnKeyNumberEvent() {

        LinkBus.registerReceiver(new ObserverAutoNext<OnKeyNumberEvent>() {
            @Override
            public Class<OnKeyNumberEvent> getBusEventClass() {
                return OnKeyNumberEvent.class;
            }

            @Override
            public void onReceiver(OnKeyNumberEvent data) {
                if (!data.isIntercepted()) {
                    if(!data.isFinally()&&SaleFunFragment.this.isExit()){
                        
                        LinkBus.unregisterReceiver(this);
                        return;
                    }

                    data.setIntercepted(true);

                    // else if("55.5".equals(data.getNumberStr()) ){


                    
                    if(!SaleFunFragment.this.isExit())
                    handNumber(data.getNumber(),data.isFinally());

                    if(SaleFunFragment.this.isExit()&&data.isFinally()){
                        
                        LinkBus.unregisterReceiver(this);
                    }
                }

            }
        });

    }

    

    
    
    public static void loadSteelyardInfo(MBaseFragment fragment){
        SteelyardDataModule steelyardDataModule = AppConst.getModuleManager().loadModule(SteelyardDataModule.class);
        Task<String,String,ResponEntity<SteelyardInfo>> task = steelyardDataModule.LoadSteelyardInfoForS(RunTimeData.steelyardInfo.getSteelyardMac());

//        String taskId = TaskIdIndex.loadSteelyardInfoTaskId(RunTimeData.steelyardInfo.getSteelyardMac());



        if(task!=null){
            
            ViewUIHelp.showProgressBar(fragment.getActivity(), "联网加载台秤信息中", "LoadSteelyardInfoForS");
            task.addBackCall(new BackCallAdapter<String,ResponEntity<SteelyardInfo>>(){
                @Override
                protected void onEnd(Task<?, String, ResponEntity<SteelyardInfo>> task, ResponEntity<SteelyardInfo> re, boolean isCancel) {
                    super.onEnd(task, re, isCancel);
                    if(!fragment.isExit()) {
                        ViewUIHelp.disProgressBar("LoadSteelyardInfoForS");
                        SteelyardInfo info = re.getData();
                        boolean isNew = info == null ? false : info.isNew;
                        ViewUIHelp.showTipsLong(fragment.getActivity(), (re.isSuccess()&&isNew)?"加载信息成功":"加载信息失败");
                    }
                }

            });
        }
    }

    

    // todo 直接拷贝自com.lkm.market2_0.m_imple.app_main.AppMainModuleImple.syncGoodsButtonToSteelyardForS 的
    public static void syncGoodsButtonToSteelyardForS(MBaseFragment fragment, Runnable runOK,final String steelyardMac) {

        ViewUIHelp.showProgressBar(fragment.getActivity(), "联网加载台秤商品信息中", "loadBreedForSTask");

        LoadBreedForSTask loadBreedForSTask = new LoadBreedForSTask(new DefaultTaskExecutor<String, String, ResponEntity<List<BreedTo>>>(true), ExpandConfig.instance.getTaskManager2()) {

            @Override
            public void onCancel() {
                super.onCancel();
                if (fragment.isExit()) return;
                ViewUIHelp.disProgressBar("loadBreedForSTask");
            }

            @Override
            public void onFinish(ResponEntity<List<BreedTo>> re) {
                super.onFinish(re);
                if (fragment.isExit()) return;

                ViewUIHelp.disProgressBar("loadBreedForSTask");
                if (re.isSuccess() && re.getData() != null) {
                    AppUIHelp.tryShowTipsSHORT( "加载成功，正在同步到称体");
                    syncGoodsButtonToSteelyard(fragment, runOK, steelyardMac, re.getData());

                } else {
                    AppUIHelp.tryShowTipsSHORT( "加载失败");
                }
            }
        };
        loadBreedForSTask.setId("loadBreedForSTask" + steelyardMac);
        loadBreedForSTask.action();
        loadBreedForSTask.setParam(steelyardMac);
        loadBreedForSTask.execTask();

    }

    private static void syncGoodsButtonToSteelyard(MBaseFragment fragment,Runnable okrun, String steelyardMac, List<BreedTo> breedTos) {

        if (fragment.isExit()) return;

        List<GoodsButtonInfoTo> goodsButtonInfoTos = new ArrayList<>(breedTos.size());

        for (BreedTo b : breedTos) {
            GoodsButtonInfoTo goodsButtonInfoTo = new GoodsButtonInfoTo(b.goods_name, b.price);
            goodsButtonInfoTos.add(goodsButtonInfoTo);
        }

        try {
            SteelyardServerModule steelyardServerModule = AppConst.getModuleManager().loadModule(SteelyardServerModule.class);
            AbsSendWriteTask absSendWriteTask = steelyardServerModule.setGoodsButton(steelyardMac, goodsButtonInfoTos);
            absSendWriteTask.addBackCall(new BackCallAdapter<Void, Boolean>() {
                @Override
                protected void onEnd(Task<?, Void, Boolean> task, Boolean aBoolean, boolean isCancel) {
                    super.onEnd(task, aBoolean, isCancel);
                    if (fragment.isExit()) return;

                    fragment.getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (fragment.isExit()) return;
                            ViewUIHelp.disProgressBar("loadBreedForSTask1");
                            if (!isCancel && aBoolean) {
                                AppUIHelp.tryShowTipsSHORT(  "同步商品信息成功");
                                if(okrun!=null)okrun.run();
                            } else {
                                AppUIHelp.tryShowTipsSHORT(  "同步商品信息异常");//这里报错
                            }
                        }
                    });


                }
            });
            ViewUIHelp.showProgressBar(fragment.getActivity(), "同步商品信息到称体", "loadBreedForSTask1");
        } catch (Exception e) {
            AppUIHelp.tryShowTipsSHORT(  "同步商品信息异常");

        }
    }
    

    @Override
    public void onChoiceChangeListener(ChoiceCard cc, IChoiceItem c, int index) {
        if (c.getIsChoice()) {
            FunItem funItem = (FunItem) c.getTag();
            float number = -1;
            try {
                number = Float.parseFloat(funItem.id);
            }catch (Exception e){e.printStackTrace();}
            handNumber(number, true);

        }

    }

    private void handNumber(float number,boolean isFinally){
        

        if(isFinally){
            if(number == 66.6f ){
                
                RouterUINavigation.getInstance().showWifi((BaseFragmentActivity) getActivity(),false);
                RouterUINavigation.getInstance().dismiss(SaleFunFragment.this);
            }else if(number == 6f ){

            }
            return;
        }
        if (number == 0f) {
            RouterUINavigation.getInstance().dismiss(SaleFunFragment.this);
            if (SaleFragment.saleFragment != null) {
                try {
                    SaleFragment.saleFragment.clearAll();
                } catch (Exception e) {
                }
            }

            if (subtotalPresenter != null) {
                subtotalPresenter.clearAll();
            }

        } else if (number == 1f) {
            RouterUINavigation.getInstance().dismiss(SaleFunFragment.this);
            if (SaleFragment.saleFragment != null) {
                try {
                    SaleFragment.saleFragment.editSubtotal(true);
                } catch (Exception e) {
                }
            }
            if (subtotalPresenter != null) {
                subtotalPresenter.inEditSubtotal();
            }

        } else if (number == 2f) {
            RouterUINavigation.getInstance().dismiss(SaleFunFragment.this);
            RouterUINavigation.getInstance().showVipOrderFix((BaseFragmentActivity) getActivity());
        }











//                    SaleFragment.saleFragment.createPrintInfo(RunTimeData.orderEntity);
//                    SaleFragment.saleFragment.printOrder();





//                presenter.printOrder(presenter.createPrintInfo(RunTimeData.orderEntity));


//            RouterUINavigation.getInstance().dismiss(SaleFunFragment.this);


        else if (number == 3f) {
            RouterUINavigation.getInstance().dismiss(SaleFunFragment.this);
            if (SaleFragment.saleFragment != null) {
                try {
                    RunTimeData.isQuickPay = false;
                    SaleFragment.saleFragment.goPayUI();
                } catch (Exception e) {
                }
            }

            if (subtotalPresenter != null) {
                subtotalPresenter.tryFullPay(DelegatePayTask.PayType_Delegate);
            }

        }else if(number== 4f){
            RouterUINavigation.getInstance().showInfoQR((BaseFragmentActivity) getActivity());
            RouterUINavigation.getInstance().dismiss(SaleFunFragment.this);
        }else if (number == 5f) {
            RouterUINavigation.getInstance().dismiss(SaleFunFragment.this);
            RouterUINavigation.getInstance().showCountNum( false);
//            RouterUINavigation.getInstance().showBarcodeResult();


        } else if (number == 7f) {
            RouterUINavigation.getInstance().dismiss(SaleFunFragment.this);
            RouterUINavigation.getInstance().showInfo((BaseFragmentActivity) getActivity());

        } else if (number == 8f) {
            PayApi.getPayInfoFromSah();
            try {
                String steelyardMac = RunTimeData.steelyardInfo.getSteelyardMac();
                syncGoodsButtonToSteelyardForS(SaleFunFragment.this, new Runnable() {
                    @Override
                    public void run() {
                        RouterUINavigation.getInstance().dismiss(SaleFunFragment.this);
                    }
                }, steelyardMac);
            } catch (Exception e) {
            }

        } else if (number == 9f) {
            PayApi.getPayInfoFromSah();
            loadSteelyardInfo(SaleFunFragment.this);
        }else if (number == (float) OnSteelyardKeyEvent.KEYCODE_GOODTIQU) {
            RouterUINavigation.getInstance().dismiss(SaleFunFragment.this);
            RouterUINavigation.getInstance().showFindBarcodeResult();
        }
        
    }


}
